﻿using System;
using System.Collections.Generic;
using System.Linq;
using VideoSeller.Business.Data;
using VideoSeller.Core.Interfaces;

namespace VideoSeller.Business.Models
{
	public class PaidModel : Repository<Paid>
	{
		private readonly IDatabaseSettingsProvider _databaseSettingsProvider;
		private readonly OnlineContentModel _onlineContentModel;

		public PaidModel(IDatabaseSettingsProvider databaseSettingsProvider, OnlineContentModel onlineContentModel)
		{
			_databaseSettingsProvider = databaseSettingsProvider;
			_onlineContentModel = onlineContentModel;
		}

		public void Pay(int onlineContentId, Guid userId, decimal value, decimal Evalue)
		{
			var payment = new Paid
				{
					OnlineContentId = onlineContentId,
					UserId = userId,
					Value = value,
					CreateTime = DateTime.Now,
                    EValue= Evalue

				};
			Insert(payment);
		}

		public List<OnlineContent> GetRecommended()
		{
			var start = DateTime.Today.AddDays(-_databaseSettingsProvider.RecommendedDays);
			var end = DateTime.Today;
			var items = from paid in Table
			            join category in DataContext.OnlineCategorizations on paid.OnlineContentId equals category.OnlineContentId
			            where !category.Category.Limited && (paid.OnlineContent.Active || (paid.OnlineContent.DownloadUrl != null && paid.OnlineContent.DownloadUrl != string.Empty && paid.OnlineContent.State > -1))
			            group paid by paid.OnlineContentId
			            into paidGroup
			            select new
				            {
					            OnlineContentId = paidGroup.Key,
					            Sum = Table.Where(x => x.CreateTime >= start && x.CreateTime <= end && x.OnlineContentId == paidGroup.Key).Sum(x => x.Value)
				            };
			var ids = items.Distinct().OrderByDescending(x => x.Sum).Take(3).Select(x => x.OnlineContentId);
			var result = ids.Select(id => _onlineContentModel.GetOnlineContent(id)).ToList();

			return result;
		}

		public void DeleteAll(IEnumerable<Paid> items)
		{
			foreach (var item in items)
			{
				var entity = Table.SingleOrDefault(x => x.Id == item.Id);

				if (entity != null)
				{
					Table.DeleteOnSubmit(entity);
				}
			}

			SubmitAllChanges();
		}
	}
}